package com.yuanli.card.utils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by layne on 2018/5/21.
 */
public class DateUtils {
    private DateUtils() {
    }

    public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYYMMDDHHMMSSMI = "yyyyMMddHHmmssSSS";
    public static final String YYYYMMDDHHMMSS_1 = "yyyyMMddHHmmss";
    public static final String YYYYMMDD = "yyyyMMdd";

    /**
     * 日期转换成时间戳
     *
     * @param date
     * @return
     */
    public static Timestamp dateToTimestamp(Date date) {
        return new Timestamp(date.getTime());
    }

    /**
     * 将 {@link Date}转化成 {@link LocalDateTime}
     *
     * @param date
     * @return
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * 将 {@link LocalDateTime}转化成 {@link Date}
     *
     * @param time
     * @return
     */
    public static Date localDateTimeToDate(LocalDateTime time) {
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.now();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }

    public static SimpleDateFormat simpleDateFormat(String pattern) {
        return new SimpleDateFormat(pattern);
    }

    public static String format(Date date,String pattern){
        SimpleDateFormat simpleDateFormat = DateUtils.simpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    /**
     * 获取日期当天最后时间
     *
     * @param endTime
     * @return
     */
    public static Date getEndTime(Date endTime) {
        if (endTime == null){
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);
        calendar.add(Calendar.DATE, 1);
        calendar.add(Calendar.MILLISECOND, -1);
        endTime = calendar.getTime();
        return endTime;
    }

}
